import {DownOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer, Dropdown} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage, history} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {ProFormGroup, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import ReactJson from 'react-json-view'
import ProForm from '@ant-design/pro-form'
import Search from "antd/es/input/Search";
import {generatePrefix, registerUser,generateKey} from '@/services/doa/grs'
import ProCard from "@ant-design/pro-card";

const PrefixAllocation = () => {


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [prefixValue, setPrefixValue] = useState("test")
  const [keyValue, setKeyValue] = useState({})
  const [submittedValue, setSubmittedValue] = useState({})
  const [preview, setPreview] = useState([{}, {}, {}, {}, {}])
  const actionRef = useRef();

  //使用useEffect来解决setState状态信息更新不及时的问题
  useEffect(()=>{
    updatePreview()
    actionRef.current.reloadAndRest()
  },[submittedValue])

  const formRef = useRef()

  const info = (msg) => {
    message.info(msg);
  };

  const updatePreview = () => {
    const data = []
    for (const key in submittedValue) {
      data.push({key: key, value: submittedValue[key], 'des': ''})
    }
    setPreview(data)
  }
  const onGeneratePrefix = () => {
    generatePrefix().then((data) => {
      setPrefixValue(data.data);

      formRef?.current?.setFieldsValue({
        prefix:data.data
      })

      const tmp = {...submittedValue}
      tmp.prefix = data.data
      tmp.doi =  data.data + '/dou.ADMIN'
      setSubmittedValue(tmp)
    })
  }

  const onGenerateKey = () => {
    generateKey({doi:prefixValue}).then((data) => {
      setKeyValue(data.data);
      formRef?.current?.setFieldsValue({
        jwkKey:data.data
      })
      const tmp = {...submittedValue}
      setSubmittedValue(tmp)
    })
  }

  const onValuesChanged = (values) => {
    console.log(values)
    setPrefixValue(values?.prefix)
    setSubmittedValue({...values, 'doi': prefixValue + '/dou.ADMIN'})
  }

  const onSubmit = () => {
    registerUser(submittedValue).then((response) => {
      if (response?.success == true) {
        info('前缀注册成功！')
        history.push('/grs/management');
      }
    })
  }

  const columns = [
    {
      dataIndex: 'key',
      title: '键',
    },
    {
      dataIndex: 'value',
      title: '值',
    },
    {
      dataIndex: 'des',
      title: '描述',
    }
  ];

  return (
    <PageContainer>
      <ProCard layout="center">
        <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <h1>前缀分配</h1>
          <ProForm
            formRef={formRef}
            onValuesChange={(_, values) => {
              onValuesChanged(values);
            }}
            onFinish={async (values) => {
              onSubmit()
              console.log(values);
            }}
          >
            <ProFormText width="md" placeholder="请输入组织名称" name="name" id='pages.grs.prefixAllocation.name'
                         rules={[
                           {
                             required: true,
                           }]}/>
            <ProFormGroup
              style={{
                marginBottom: 24,
              }}
            >
              <ProFormText width="md"  placeholder="请输入分配的前缀" name="prefix"
                               id='pages.grs.prefixAllocation.prefix'
                               rules={[
                                 {
                                   required: true,
                                 }]}/>
              <Button type="primary" onClick={onGeneratePrefix}>自动生成前缀</Button>
            </ProFormGroup>
            <ProFormGroup>
              <ProFormTextArea width="md" autoSize={true} placeholder="请输入密钥信息" name="jwkKey"
                               id='pages.grs.prefixAllocation.jwkKey'
                               rules={[
                                 {
                                   required: true,
                                 }]}/>
              <Button type="primary" onClick={onGenerateKey}>自动生成密钥</Button>
            </ProFormGroup>
            <ProFormTextArea width="md" autoSize={true} placeholder="请输入服务地址" name="serviceAddress"
                             id='pages.grs.prefixAllocation.serviceAddress'
                             rules={[
                               {
                                 required: true,
                               }]}/>
          </ProForm>
        </ProCard>
        <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <h1>信息预览</h1>
          <ProTable
            columns={columns}
            request={(params, sorter, filter) => {
              return Promise.resolve({
                data: preview,
                success: true,
              });
            }}
            actionRef={actionRef}
            rowKey="preview"
            pagination={{
              showQuickJumper: true,
            }}
            options={false}
            toolBarRender={false}
            search={false}
          />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};

export default PrefixAllocation;
